package com.ailot.cloud.base.security.utils;


import cn.hutool.json.JSONUtil;
import com.ailot.cloud.base.security.authentication.model.JwtUser;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
public class JWTUtil {


    /**
     * 秘钥
     */
    private static String secret = "1PtxrRwPDIpeDfwu";

    @Value("${jwt.secret:1PtxrRwPDIpeDfwu}")
    public void setSecret(String secret) {
        JWTUtil.secret = secret;
    }

    /**
     * 令牌过期时间(小时)
     */
    private static Long expire = 24L;

    @Value("${jwt.expire:24}")
    public void setExpire(Long expire) {
        JWTUtil.expire = expire;
    }

    public static final String ID = "id";
    public static final String ORGID = "orgId";
    public static final String USERNAME = "username";
    public static final String AUTHORITIES = "authorities";


    /**
     * 生成token
     *
     * @param jwtUser
     * @return
     */
    public static String createToken(JwtUser jwtUser) {
        // 签名算法 ，将对token进行签名
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        Map<String, Object> claims = Maps.newHashMap();
        claims.put(ID, jwtUser.getId());
        claims.put(ORGID, jwtUser.getOrgId());
        claims.put(USERNAME, jwtUser.getUsername());
        List<GrantedAuthority> list = jwtUser.getAuthorities().stream().collect(Collectors.toList());
        List<String> stringList = list.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        claims.put(AUTHORITIES, JSONUtil.toJsonStr(stringList));
        return Jwts
                .builder()
                .setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expire * 60 * 60 * 1000))
                .signWith(signatureAlgorithm, signingKey).compact();
    }

    /**
     * 检查token是否有效
     *
     * @param token the token
     * @return the claims
     */
    public static Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("验证token出错:{}", e.getMessage());
            return null;
        }
    }

    /**
     * 判断是否过期
     *
     * @param claims
     * @return
     */
    public static boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

    /**
     * true 无效
     * false 有效
     *
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if (claims != null) {
            return isTokenExpired(claims);
        }
        return true;
    }
}
